﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Teamcenter.Services.Strong.Core._2010_04.Session;
using Teamcenter.Services.Strong.Core._2007_01.Session;
using Teamcenter.Soa.Client.Model;
using Teamcenter.Services.Strong.Core._2006_03.Session;
using Teamcenter.Soa.Client.Model;
using Teamcenter.Services.Internal.Strong.Core._2011_06.ICT;
using Teamcenter.Services.Strong.Workflow;
using Teamcenter.Services.Strong.Workflow._2010_09.Workflow;
using Teamcenter.Services.Strong.Workflow._2008_06.Workflow;
namespace TC4T_WinForm
{
    public partial class WorkFlowForm :TCForm
    {
        public WorkFlowForm()
        {
            InitializeComponent();
        }
        MultiPreferenceResponse2 r;
        //Dictionary<string, string> preferenceuid = new Dictionary<string, string>();

        private void bt_setPreference_Click(object sender, EventArgs e)
        {
            ScopedPreferenceNames p = new ScopedPreferenceNames();
            p.Scope="all";
            p.Names = new string[]{"HistoryTypeList","HistoryIDList"};
            r = TCHelper.GetPreferences(new ScopedPreferenceNames[] { p });
            if (r != null)
            {
                if (r.Preferences != null &&
                    r.Preferences.Length > 0)
                {
                    foreach (ReturnedPreferences2 r2 in r.Preferences)
                    {
                        richTextBox1.Text += "name:"+ r2.Name + "\n";
                        foreach (string value in r2.Values)
                        {
                            richTextBox1.Text += "\n  " + "value:" + value + "\n";
                        }
                    }
                }
            }
        }

        private void bt_getinboxObject_Click(object sender, EventArgs e)
        {
            ModelObject mo = MyTCSession.LoginUser.Userinbox;
            if (mo != null)
            {
                //ServiceData sd = TCHelper.LoadObjects(new string[] { mo.Uid });
                //ModelObject m1 = sd.GetPlainObject(0);
                //ServiceData s1 = TCHelper.GetPropertyValues(new ModelObject[] { m1 }, new string[] { "contents" });
                //if (s1 != null)
                //{
                //    string[] ret = TCHelper.GetPropertyValuesByServiceData(s1, 0, "contents");
                //    if (ret != null)
                //    {
                //        richTextBox1.Text += ret[0];
                //        richTextBox1.Text += "\n" + s1.GetPlainObject(0).Uid;
                //    }
                //}

                Dictionary<string, Dictionary<string,Property>> dic =null;

                dic = TCHelper.GetPropertiesByUids(new string[] { mo.Uid }, new string[] { "contents" });
                if (dic != null)
                {//task inbox
                    Property p_task_inbox = dic[mo.Uid]["contents"];
                    string task_inbox_uid = p_task_inbox.ModelObjectArrayValue[0].Uid;
                    Dictionary<string, Dictionary<string,Property>> dic1
                        = TCHelper.GetPropertiesByUids(new string[] { p_task_inbox.ModelObjectArrayValue[0].Uid }
                        , new string[] { "contents", "new_tasks_count", "new_tasks_flag" });

                    if (dic1 != null)
                    {//two
                        Property twoproperty = dic1[task_inbox_uid]["contents"];
                        if (twoproperty != null)
                        {
                            ModelObject[] mos = twoproperty.ModelObjectArrayValue;
                            string[] tUids =
                            new string[] { mos[0].Uid, mos[1].Uid };
                            string[] atts = new string[] { "contents" };
                            Dictionary<string, Dictionary<string, Property>>
                                tdic = TCHelper.GetPropertiesByUids(tUids, atts);
                            if (tdic != null)
                            {
                                Property tp1 = tdic[tUids[0]]["contents"];
                                Property tp2 = tdic[tUids[1]]["contents"];

                                if (tp2 != null)
                                {
                                    
                                }
                            }
                        }
                    }
                }
            }
        }

        private void bt_gettemplate_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> pair;
            EPMHelper.GetAllEPMTemplates(out pair);
            if (pair != null)
            {
 
            }
            ModelObject[] perform,track;
             EPMHelper.GetTaskPerformAndTaskTrack(out perform,out track);
             if (perform != null)
             {
                 richTextBox1.Text += "perform:\n";
                 richTextBox1.Text += "count:" + perform.Length;
                 richTextBox1.Text += "\n track:\n";
                 richTextBox1.Text += "count:" + track.Length;
             }
        }

        /// <summary>
        /// #define EPM_target_attachment           1 
            //#define EPM_reference_attachment        3 
            //#define EPM_signoff_attachment          4 
            //#define EPM_release_status_attachment   5 
            //#define EPM_comment_attachment          6 
            //#define EPM_instruction_attachment      7 
            //#define EPM_interprocess_task_attachment    8 
            //#define EPM_project_task_attachment     9 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_createprocess_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
                return;
            string itemNo = textBox1.Text.Trim();
            string msg;
            bool isOk = EPMHelper.CreateProcess(itemNo, "test",out msg);
            if (isOk == false)
                richTextBox1.Text += msg + "\n";

        }

        private void button1_Click(object sender, EventArgs e)
        {

            Dictionary<string,string> dic;
            EPMHelper.GetAllEPMTemplates(out dic);
            if (dic != null)
            {
                foreach (KeyValuePair<string, string> pair in dic)
                {
                    richTextBox1.Text += pair.Key + " " + pair.Value + "\n";
                }
                Dictionary<string, ModelObject> nameMoDic;
                EPMHelper.TemplateGetChildrenInfo(dic["CMII Change Request"], EPMTemplateCPPClassNames.EPMTaskTemplate, out nameMoDic);
                if (nameMoDic != null)
                {
                    Dictionary<string, ModelObject> subDic;
                    EPMHelper.TemplateGetChildrenInfo(nameMoDic["Author Technical Recommendation"].Uid, EPMTemplateCPPClassNames.EPMReviewTaskTemplate, out subDic);
                    if (subDic != null)
                    {
                        ModelObject user = EPMHelper.GetGroupByGroupName("Engineering");
                        if (user != null)
                        { }
                    }
                }
            }
        }

        private void bt_testUserRelated_Click(object sender, EventArgs e)
        {
            Arg[] args = new Arg[2];
            Arg arg1 = new Arg(); arg1.Val = "Group";
            Arg arg2 = new Arg(); arg2.Val = "TYPE::Group::Group::POM_group";
            args[0] = arg1; args[1] = arg2;
            Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.InvokeICTMethodResponse r1 = TCHelper.InvokeICTMethod("ICCTGroup", "getRootGroupAndIconIdList", args);
            if (r1 != null)
            {
                args = new Arg[3];
                arg1 = new Arg(); arg2 = new Arg(); Arg arg3 = new Arg();
                arg1.Val = "User"; arg2.Val = "TYPE::User::User::POM_user"; arg3.Val = "xiaojin";
                args[0] = arg1; args[1] = arg2; args[2] = arg3;
                Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.InvokeICTMethodResponse r_user = TCHelper.InvokeICTMethod("ICCTUser", "find", args);
                if (r_user != null)
                {
                    ModelObject mo = r_user.ServiceData.GetPlainObject(0);
                    if (mo != null)
                    {
                        string name = mo.GetPropertyDisplayableValues("user_name")[0];
                        if (name != null)
                        {
 
                        }
                    }
                }
            }
        }

        private void bt_performaction_Click(object sender, EventArgs e)
        {
            //Arg[] args = new Arg[3];
            //Arg arg1 = new Arg(); Arg arg2 = new Arg(); Arg arg3 = new Arg();
            //arg1.Val = "User"; arg2.Val = "TYPE::User::User::POM_user"; arg3.Val = "xiaojin";
            //args[0] = arg1; args[1] = arg2; args[2] = arg3;
            //Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.InvokeICTMethodResponse r_user = TCHelper.InvokeICTMethod("ICCTUser", "find", args);
            //ModelObject mo_user = null;
            //if (r_user != null)
            //{
            //    mo_user = r_user.ServiceData.GetPlainObject(0);
            //    if (mo_user != null)
            //    {
            //        string name = mo_user.GetPropertyDisplayableValues("user_name")[0];
            //        if (name != null)
            //        {
            //            //find user
            //        }
            //    }
            //}

            //ModelObject mo_item = TCHelper.QueryItemByItemID("000095");
            //Dictionary<string, Dictionary<string, Property>> dic
            //        = TCHelper.GetPropertiesByUids(new string[] { mo_item.Uid }, new string[] { "process_stage", "process_stage_list" });
            //if (dic != null)
            //{
            //    Property p = dic[mo_item.Uid]["process_stage"];
            //    if (p != null)
            //    {
            //        string[] sarray = p.DisplayableValues;
            //        if (sarray != null && sarray.Length >= 0)
            //            if (!string.IsNullOrEmpty(sarray[0]))
            //            {
            //                Property process_stage_list = dic[mo_item.Uid]["process_stage_list"];
            //                ModelObject EPMTaskMO = process_stage_list.ModelObjectArrayValue[0];
            //                Teamcenter.Soa.Client.Model.Strong.EPMDoTask dotask =
            //                    (Teamcenter.Soa.Client.Model.Strong.EPMDoTask)process_stage_list.ModelObjectArrayValue[1];
            //                Teamcenter.Soa.Client.Model.Strong.EPMTask task = (Teamcenter.Soa.Client.Model.Strong.EPMTask)EPMTaskMO;

            //                Arg[] args1 = new Arg[6];
            //                Arg arg11 = new Arg(); arg11.Val="EPMTaskTemplate";
            //                Arg arg21 =new Arg(); arg21.Val="TYPE::EPMDoTaskTemplate::EPMTaskTemplate::EPMTaskTemplate";
            //                Arg arg31 = new Arg(); arg31.Val = "wVWFoaBs40fgGC";//dotask.Uid;
            //                Arg arg41 =new Arg(); arg41.Val="0";
            //                Arg arg51 = new Arg(); arg51.Val = "4";
            //                Arg arg61 =new Arg(); arg61.Val ="EPM-hold";
            //                args1[0] = arg11;args1[1]=arg21;
            //                args1[2] = arg31;args1[3] = arg41;args1[4] = arg51;args1[5] = arg61;

            //                Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.InvokeICTMethodResponse r_handler=
            //                TCHelper.InvokeICTMethod("ICCTTaskTemplate", "getHandler", args1);
            //                if (r_handler != null)
            //                {
            //                    Arg[] argset = new Arg[5];
            //                    Arg setarg1 = new Arg(); setarg1.Val = "EPMTask";
            //                    Arg setarg2 = new Arg(); setarg2.Val = "TYPE::EPMDoTask::EPMTask::EPMTask";
            //                    Arg setarg3 = new Arg(); setarg3.Val = r_handler.Output[0].Val;

            //                    Arg setarg4 = new Arg(); Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Array array1 = new Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Array();
            //                    Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Entry[] en1s = new Entry[2];
            //                    Entry en11 = new Entry(); en11.Val = "done";
            //                    Entry en12 = new Entry(); en12.Val = "comments";
            //                    en1s[0] = en11; en1s[1] = en12;
            //                    array1.Entries = en1s;
            //                    setarg4.Array = new Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Array[] { array1 };

            //                    Arg setarg5 = new Arg();
            //                    Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Array array2 = new Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Array();
            //                    Entry en21 = new Entry();
            //                    Structure s1 = new Structure();
            //                    s1.Args = new Arg[2];
            //                    Arg s11 = new Arg(); s11.Val = "true";
            //                    Arg s12 = new Arg(); s12.Val = "true";
            //                    s1.Args[0] = s11; s1.Args[1] = s12;
            //                    en21.Structure = new Structure[] { s1 };

            //                    Entry en22 = new Entry();
            //                    Structure s2 = new Structure();
            //                    s2.Args = new Arg[2];
            //                    Arg s21 = new Arg(); s21.Val = "true";
            //                    Arg s22 = new Arg(); s22.Val = "";
            //                    s2.Args[0] = s21; s2.Args[1] = s22;
            //                    en22.Structure = new Structure[] { s2 };
            //                    array2.Entries = new Entry[2] { en21, en22 };
            //                    setarg5.Array = new Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Array[] { array2 };
            //                    Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.InvokeICTMethodResponse r_setproperty =
            //                TCHelper.InvokeICTMethod("ICCT", "setProperties", args1);
            //                    if (r_setproperty != null)
            //                    {
            //                    }
            //                }
            //WorkflowService ws = WorkflowService.getService(MyTCSession.MySessionConnection);
            //ServiceData sd = ws.PerformAction(dotask, "SOA_EPM_complete_action", "肖劲0", null, "SOA_EPM_unset", mo_user);
            string itemNo = textBox2.Text;
            if (string.IsNullOrEmpty(itemNo))
                return;
            Dictionary<string, string> allTample;
            string currentDOtaskUid="";
            EPMHelper.GetAllEPMTemplates(out allTample);
            if (allTample != null)
            {
                Dictionary<string,ModelObject> testTemplate;
                EPMHelper.TemplateGetChildrenInfo(allTample["test"], EPMTemplateCPPClassNames.EPMTaskTemplate, out testTemplate);
                if (testTemplate != null)
                {
                    ModelObject mo_item = TCHelper.QueryItemByItemID(itemNo);
                    Dictionary<string, Dictionary<string, Property>> dicPro = TCHelper.GetPropertiesByUids
                        (new string[] { mo_item.Uid }, new string[] { ItemEMPPropertyNames.process_stage_list.ToString() });
                    if (dicPro != null)
                    {
                        ModelObject taskMO = dicPro[mo_item.Uid][ItemEMPPropertyNames.process_stage_list.ToString()].ModelObjectArrayValue[1];

                        Teamcenter.Soa.Client.Model.Strong.EPMTask dotask
                            =(Teamcenter.Soa.Client.Model.Strong.EPMTask)taskMO;

                        string taskName = dicPro[mo_item.Uid][ItemEMPPropertyNames.process_stage_list.ToString()].DisplayableValues[1];

                        currentDOtaskUid = testTemplate[taskName].Uid;
                        EPMHelper.ReleaseEMPHold(currentDOtaskUid,taskMO.Uid ,"肖劲测试");
                        
                        //WorkflowService ws = WorkflowService.getService(MyTCSession.MySessionConnection);

                        //ModelObject mo_user = EPMHelper.GetUserByLoginName("xiaojin");
                        //ServiceData sd = ws.PerformAction(dotask, "SOA_EPM_perform_action", "肖劲0", null, "SOA_EPM_completed", null);
                        //if (sd != null)
                        //{

                        //}
                        List<Arg> args = new List<Arg>();
                        Arg arg1 = new Arg(); arg1.Val = "EPMTask";
                        Arg arg2 = new Arg(); arg2.Val = "TYPE::EPMDoTask::EPMTask::EPMTask";
                        Arg arg3 = new Arg(); arg3.Val = dotask.Uid;
                        Arg arg4 = new Arg(); arg4.Val = "4";
                        Arg arg5 = new Arg(); arg5.Val = "你好啊";
                        args.Add(arg1); args.Add(arg2); args.Add(arg3);
                        args.Add(arg4); args.Add(arg5);

                        InvokeICTMethodResponse reponse =
                            TCHelper.InvokeICTMethod("ICCTTask", "performAction", args.ToArray());
                        if (reponse != null)
                        {

                        }
                    }
                }
            }
        }

        private void bt_inbox_first_Click(object sender, EventArgs e)
        {
            ModelObject[] performs,tracks;
            EPMHelper.GetTaskPerformAndTaskTrack(out performs, out tracks);
            if (performs!=null && performs.Length > 0)
            {
                ModelObject mo_first = performs[0];
                if (mo_first.GetPropertyDisplayableValue("object_type")
                    == "EPMPerformSignoffTask")
                {
                    Dictionary<string,Dictionary<string,Property>> dic
                        =TCHelper.GetPropertiesByUids(new string[] { mo_first.Uid },
                        new string[] { "parent_task" });
                    Property p = dic[mo_first.Uid]["parent_task"];

                    ModelObject root_task = p.ModelObjectValue;
                    
                    WorkflowService ws = WorkflowService.getService(MyTCSession.MySessionConnection);
                    Teamcenter.Soa.Client.Model.Strong.EPMTask roottask = (Teamcenter.Soa.Client.Model.Strong.EPMTask)root_task;
                    ServiceData sd = ws.PerformAction(roottask, "SOA_EPM_perform_action", "肖劲0", null, "SOA_EPM_approve", mo_first);
                    if (sd != null)
                    {

                    }
                }
            }
        }
    }
}
